<template>
  <div class="container">
    <TableWrapper :title="'字典管理'">
      <!-- 搜索头 -->
      <template #header>
        <el-form ref="form" :model="query" label-width="100px" :inline="true">
          <el-form-item label="字典名称：">
            <el-input
              style="width: 220px"
              v-model="query.dictName"
              placeholder="请输入字典名称"
            ></el-input>
          </el-form-item>

          <el-form-item label="字典类型：">
            <el-input
              style="width: 220px"
              v-model="query.dictType"
              placeholder="请输入字典名称"
            ></el-input>
          </el-form-item>

          <el-form-item label="字典状态：">
            <el-select
              v-model="query.status"
              style="width: 220px"
              placeholder="请选择字典状态"
            >
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间：">
            <el-date-picker
              style="width: 220px"
              v-model="query.createTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item class="ml15">
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="searchChange"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh-left" @click="searchReset"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </template>

      <!-- 表体 -->
      <template #main>
        <div style="margin-bottom: 18px">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="beforeOpen('add')"
            v-hasPermission="['system:dict:add']"
            >新增</el-button
          >
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="selectionList.length == 0"
            v-hasPermission="['system:dict:delete']"
            >批量删除</el-button
          >
          <el-button
            type="success"
            @click="refreshChange"
            plain
            icon="el-icon-refresh"
            v-hasPermission="['system:dict:query']"
            >刷新缓存</el-button
          >
        </div>
        <el-table
          :data="data"
          :header-cell-style="headStyle"
          @selection-change="selectionChange"
        >
          <el-table-column align="center" type="selection" width="60">
          </el-table-column>
          <el-table-column align="center" prop="dictId" label="字典编号">
          </el-table-column>
          <el-table-column align="center" prop="dictName" label="字典名称">
          </el-table-column>
          <el-table-column align="center" prop="dictType" label="字典类型">
            <template slot-scope="scope">
              <el-button
                @click="$emit('queryData', 'edit', scope.row)"
                type="text"
                >{{ scope.row.dictType }}</el-button
              >
            </template>
          </el-table-column>
          <el-table-column align="center" prop="status" label="状态">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_normal_disable"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间">
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-edit"
                size="small"
                @click="beforeOpen('edit', scope.row)"
                v-hasPermission="['system:dict:edit']"
                >编辑</el-button
              >
              <el-button
                @click="handelDel(scope.row)"
                type="text"
                icon="el-icon-delete"
                v-hasPermission="['system:dict:delete']"
                size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>

      <template #footer>
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </template>
    </TableWrapper>

    <!-- 修改框 -->
    <el-dialog
      :title="(ntype == 'add' ? '添加' : '修改') + '字典类型'"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="字典名称：" prop="dictName">
          <el-input
            v-model="form.dictName"
            placeholder="请输入字典名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典类型：" prop="dictType">
          <el-input
            v-model="form.dictType"
            placeholder="请输入字典类型"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio-group value="0" v-model="form.status">
            <el-radio
              v-for="item in dict.type.sys_normal_disable"
              :key="item.raw.dictCode"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            placeholder="请输入备注内容"
            maxlength="500"
            type="textarea"
            resize="none"
            show-word-limit
            v-model="form.remark"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave()" :loading="loading"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableWrapper from "@/components/Table/TableWrapper.vue";
import {
  getList,
  getNotice,
  add,
  update,
  remove,
} from "@/api/system/dictType.js";

export default {
  dicts: ["sys_normal_disable"],
  components: { TableWrapper },
  data() {
    return {
      // 搜索数据
      query: {},
      // 多选数据
      selectionList: [],
      // 表数据
      data: [],
      // 弹出框数据
      form: {},
      // 表单验证规则
      rules: {
        dictName: [
          { required: true, message: "字典名称不能为空", trigger: "blur" },
          { max: 100, message: "长度不允许超过100个字符", trigger: "blur" },
        ],
        dictType: [
          { required: true, message: "字典类型不能为空", trigger: "blur" },
          { max: 100, message: "长度不允许超过100个字符", trigger: "blur" },
        ],
      },
      // 分页数据
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      // 控制弹出框
      dialogVisible: false,
      // 操作类型
      ntype: "add",
      // 按钮
      loading: false,
      // 校验结果
      validate: false,
    };
  },
  created() {
    // 获取数据
    this.refreshChange();
    // 重置表单
    this.resetForm();
  },
  methods: {
    // 搜索重置
    searchReset() {
      this.query = {};
      this.refreshChange();
    },
    // 搜索点击
    searchChange() {
      this.refreshChange();
    },
    // 多选发生改变
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
    },
    // 当前分页发生改变
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.refreshChange();
    },
    // 分页大小发生改变
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.refreshChange();
    },
    // 刷新数据
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    // 重置表单
    resetForm() {
      this.form = {
        dictId: undefined,
        dictName: undefined,
        dictType: undefined,
        status: "0",
        remark: undefined,
      };
    },
    // 校验表单
    validateForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.validate = true;
          return true;
        } else {
          this.validate = false;
          return false;
        }
      });
    },
    // 处理表单开启
    beforeOpen(ntype, row) {
      this.ntype = ntype;
      // 重置标签
      this.resetForm();

      // 如果是编辑
      if (["edit", "view"].includes(ntype)) {
        // 查询详情
        getNotice(row.dictId).then((res) => {
          this.form = res.data;
        });
      }

      // 修改按钮状态
      this.loading = false;
      // 打开提交框
      this.dialogVisible = true;
    },
    // 添加数据
    handleSave() {
      // 校验表单
      this.validateForm();

      if (!this.validate) {
        return;
      }

      if (this.ntype == "add") {
        this.sendAjax(add, this.form);
      } else {
        this.sendAjax(update, this.form);
      }
    },
    // 发送 ajax 请求
    sendAjax(Interface, row) {
      // 调用接口发送请求
      Interface(row).then(
        (res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
            // 关闭弹窗
            this.dialogVisible = false;
            // 刷新列表
            this.refreshChange();
          } else {
            this.$modal.msgError(res.msg);
          }
          this.loading = false;
        },
        () => {
          this.$modal.msgError("系统错误，请稍后尝试！");
        }
      );
    },
    // 删除数据
    handelDel(row) {
      this.$modal
        .confirm("确定将选择数据删除?")
        .then(() => {
          return remove(row.dictId);
        })
        .then(() => {
          this.refreshChange();
          this.$modal.msgSuccess("操作成功!");
        });
    },
    // 重载数据
    onLoad(page, params = {}) {
      let values = {
        ...params,
        // 排序字段
        orderByColumn: "create_time",
        // 排序方式 desc 降序 asc 升序
        isAsc: "asc",
      };

      // 传递日期
      if (values.createTime && values.createTime.length == 2) {
        values.beginTime = params.createTime[0];
        values.endTime = params.createTime[1];
      }

      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(values, this.query)
      ).then((res) => {
        const data = res.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 自定义表头颜色
    headStyle({ row, rowIndex }) {
      if (rowIndex === 0) {
        return {
          backgroundColor: "#F8FAFF",
          fontWeight: 800,
          color: "#515a6e",
        };
      }
    },
  },
};
</script>